package com.gemini.main.concurrent;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;


/**
 * 使用信号量实现一个有界阻塞容器
 * @param <T>
 */
public class BoundedHashSet<T> {

    private final Set<T> set;
    private final Semaphore semaphore;

    public BoundedHashSet(int bound) {
        this.set = Collections.synchronizedSet(new HashSet<T>());
        semaphore = new Semaphore(bound);
    }

    public boolean add(T o) throws InterruptedException {
        semaphore.acquire();
        boolean addFlag = false;
        try {
            addFlag = set.add(o);
            return addFlag;
        } finally {
            if (!addFlag)
            semaphore.release();
        }
    }

    public boolean remove(T o) {
        boolean removeFlag = set.remove(o);
        if (removeFlag)
            semaphore.release();
        return removeFlag;
    }
}
